#!/user/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer, Boolean, TIMESTAMP, UnicodeText
from sqlalchemy.sql import func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

""" topic_img_item collection has
    id:             自增id（int）
    topicid:        话题id（int）
    noteid:         内容id（int）
    place:          位置信息（string）
    ctime:          添加时间（datetime）
"""

class TopicNotePlaceItem(object):
    def to_dict(self):
        res = {}
        res['topicid'] = self.topicid
        res['noteid'] = self.noteid
        res['place'] = self.place
        res['ctime'] = ''
        if self.ctime:
            res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S")
        return res

    def __repr__(self):
        return "%d" % (self.noteid)


topic_note_place_table = Table(
    'topic_note_place', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('topicid', Integer, nullable=False),
    Column('noteid', Integer, index=True, nullable=False),
    Column('place', UnicodeText, nullable=True),
    Column('ctime', TIMESTAMP, server_default=func.now()),
)

mapper(TopicNotePlaceItem, topic_note_place_table)


def create_topic_note_place_table_if_not_exist():
    metadata.create_all(engine)


def add_topic_note_place_item(p_item):
    item = TopicNotePlaceItem()
    item.topicid = p_item['topicid']
    item.noteid = p_item['noteid']
    item.place = p_item['place']

    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def get_topic_note_place_by_noteid_list(p_noteid_list):
    try:
        session = Session()
        items = session.query(TopicNotePlaceItem),filter(TopicNotePlaceItem.noteid.in_(p_noteid_list)).all()


    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()




def get_topic_note_img_map_by_noteid_list(p_noteid_list):
    try:
        session = Session()
        items = session.query(TopicNoteImgItem)\
            .filter(TopicNoteImgItem.noteid.in_(p_noteid_list)).all()

        note_img_dict_map = {}
        note_img_map = {}
        for item in items:
            if item.noteid not in note_img_dict_map:
                note_img_dict_map[item.noteid] = {}
            note_img_dict_map[item.noteid][item.imgseq] = item.imglink
        for noteid in note_img_dict_map:
            tmp_dict = note_img_dict_map[noteid]
            note_img_map[noteid] = [tmp_dict[key]
                                    for key in sorted(tmp_dict)]
        return note_img_map
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()





